import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import {
  makeStyles,
  Card,
  Button,
  Badge,
  Spinner,
} from '@fluentui/react-components';
import {
  ArrowTrending20Regular,
  ContactCard20Regular,
  DocumentBulletList20Regular,
  Alert20Regular,
  Eye20Regular,
} from '@fluentui/react-icons';
import { PieChart, Pie, Cell, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { RootState } from '../store/store';
import { setStats, setTodos, setActivities, setOpportunityDistribution, setHighValueOpportunities } from '../store/slices/dashboardSlice';

const useStyles = makeStyles({
  dashboard: {
    display: 'flex',
    flexDirection: 'column',
    gap: '24px',
    height: '100%',
  },
  statsGrid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
    gap: '16px',
  },
  statCard: {
    padding: '24px',
    borderRadius: '8px',
    border: '1px solid #E5E6EB',
  },
  statHeader: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: '16px',
  },
  statIcon: {
    padding: '8px',
    borderRadius: '6px',
    fontSize: '20px',
  },
  statIconPrimary: {
    backgroundColor: '#F0F4FF',
    color: '#165DFF',
  },
  statIconSuccess: {
    backgroundColor: '#E8F5E8',
    color: '#00B42A',
  },
  statIconWarning: {
    backgroundColor: '#FFF3E8',
    color: '#FF7D00',
  },
  statIconInfo: {
    backgroundColor: '#F0F0F0',
    color: '#86909C',
  },
  statValue: {
    fontSize: '32px',
    fontWeight: '600',
    color: '#1D2129',
    lineHeight: 1,
  },
  statLabel: {
    fontSize: '14px',
    color: '#86909C',
    marginTop: '4px',
  },
  statChange: {
    fontSize: '12px',
    marginTop: '8px',
    display: 'flex',
    alignItems: 'center',
    gap: '4px',
  },
  changePositive: {
    color: '#00B42A',
  },
  changeNegative: {
    color: '#F53F3F',
  },
  mainContent: {
    display: 'grid',
    gridTemplateColumns: '2fr 1fr',
    gap: '24px',
    '@media (max-width: 1024px)': {
      gridTemplateColumns: '1fr',
    },
  },
  leftColumn: {
    display: 'flex',
    flexDirection: 'column',
    gap: '24px',
  },
  rightColumn: {
    display: 'flex',
    flexDirection: 'column',
    gap: '24px',
  },
  cardHeader: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: '16px',
  },
  cardTitle: {
    fontSize: '16px',
    fontWeight: '600',
    color: '#1D2129',
  },
  cardContent: {
    padding: '24px',
  },
  todoItem: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '12px 0',
    borderBottom: '1px solid #F2F3F5',
  },
  todoInfo: {
    flex: 1,
  },
  todoTitle: {
    fontSize: '14px',
    fontWeight: '500',
    color: '#1D2129',
    marginBottom: '4px',
  },
  todoMeta: {
    fontSize: '12px',
    color: '#86909C',
  },
  priorityBadge: {
    marginLeft: '8px',
  },
  activityItem: {
    display: 'flex',
    gap: '12px',
    padding: '12px 0',
    borderBottom: '1px solid #F2F3F5',
  },
  activityDot: {
    width: '8px',
    height: '8px',
    borderRadius: '50%',
    marginTop: '6px',
    flexShrink: 0,
  },
  activityContent: {
    flex: 1,
  },
  activityTitle: {
    fontSize: '14px',
    color: '#1D2129',
    marginBottom: '4px',
  },
  activityTime: {
    fontSize: '12px',
    color: '#86909C',
  },
  chartContainer: {
    height: '300px',
    width: '100%',
  },
  highValueItem: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '16px 0',
    borderBottom: '1px solid #F2F3F5',
  },
  highValueInfo: {
    flex: 1,
  },
  highValueName: {
    fontSize: '14px',
    fontWeight: '500',
    color: '#1D2129',
    marginBottom: '4px',
  },
  highValueCustomer: {
    fontSize: '12px',
    color: '#86909C',
  },
  highValueMeta: {
    textAlign: 'right',
  },
  highValueAmount: {
    fontSize: '16px',
    fontWeight: '600',
    color: '#165DFF',
    marginBottom: '4px',
  },
  emptyState: {
    textAlign: 'center',
    padding: '40px 20px',
    color: '#86909C',
  },
  loadingContainer: {
    display: 'flex',
    justifyContent: 'center',
    padding: '40px',
  },
});

const DashboardPage: React.FC = () => {
  const classes = useStyles();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { stats, todos, activities, opportunityDistribution, highValueOpportunities, loading } = useSelector(
    (state: RootState) => state.dashboard
  );

  // 模拟数据加载
  useEffect(() => {
    const loadDashboardData = async () => {
      // 模拟统计数据
      const mockStats = {
        totalOpportunities: 156,
        activeOpportunities: 89,
        weeklyNew: 12,
        monthlyClosedWon: 8,
        totalValue: 8500000,
        conversionRate: 23.5,
      };

      // 模拟待办事项
      const mockTodos = [
        {
          id: '1',
          type: 'follow_up' as const,
          title: '跟进阿里巴巴云服务项目',
          description: '需要在本周内联系客户确认技术方案',
          dueDate: '2024-07-26',
          priority: 'high' as const,
          opportunityId: 'opp1',
        },
        {
          id: '2',
          type: 'approval' as const,
          title: '审批腾讯广告投放计划',
          description: '商务计划等待最终审批',
          dueDate: '2024-07-27',
          priority: 'medium' as const,
          opportunityId: 'opp2',
        },
        {
          id: '3',
          type: 'deadline' as const,
          title: '字节跳动合作协议到期提醒',
          description: '需要在下周前续签合作协议',
          dueDate: '2024-07-30',
          priority: 'high' as const,
          opportunityId: 'opp3',
        },
      ];

      // 模拟活动记录
      const mockActivities = [
        {
          id: '1',
          type: 'opportunity_created' as const,
          title: '创建了新商机：百度AI解决方案',
          description: '价值500万的AI技术服务项目',
          timestamp: '2024-07-25T10:30:00Z',
          user: '张三',
        },
        {
          id: '2',
          type: 'plan_generated' as const,
          title: '生成了商务计划',
          description: '为微软Azure项目生成了AI商务计划',
          timestamp: '2024-07-25T09:15:00Z',
          user: '李四',
        },
        {
          id: '3',
          type: 'risk_reported' as const,
          title: '上报了风险',
          description: 'AWS项目技术风险需要关注',
          timestamp: '2024-07-25T08:45:00Z',
          user: '王五',
        },
      ];

      // 模拟商机分布数据
      const mockOpportunityDistribution = [
        { name: '初步接触', value: 35, color: '#FF7D00' },
        { name: '需求沟通', value: 28, color: '#165DFF' },
        { name: '方案制定', value: 18, color: '#00B42A' },
        { name: '商务谈判', value: 12, color: '#86909C' },
        { name: '已成单', value: 7, color: '#F53F3F' },
      ];

      // 模拟高价值商机
      const mockHighValueOpportunities = [
        {
          id: '1',
          name: '阿里云数字化转型项目',
          value: 12000000,
          customer: '阿里巴巴集团',
          risk: 'low' as const,
        },
        {
          id: '2',
          name: '腾讯游戏云服务',
          value: 8500000,
          customer: '腾讯科技',
          risk: 'medium' as const,
        },
        {
          id: '3',
          name: '字节跳动广告系统',
          value: 6800000,
          customer: '字节跳动',
          risk: 'high' as const,
        },
      ];

      dispatch(setStats(mockStats));
      dispatch(setTodos(mockTodos));
      dispatch(setActivities(mockActivities));
      dispatch(setOpportunityDistribution(mockOpportunityDistribution));
      dispatch(setHighValueOpportunities(mockHighValueOpportunities));
    };

    loadDashboardData();
  }, [dispatch]);

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(amount);
  };

  const formatNumber = (num: number) => {
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + '万';
    }
    return num.toString();
  };

  const getRiskColor = (risk: string) => {
    switch (risk) {
      case 'high': return '#F53F3F';
      case 'medium': return '#FF7D00';
      case 'low': return '#00B42A';
      default: return '#86909C';
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'high': return 'danger';
      case 'medium': return 'warning';
      case 'low': return 'success';
      default: return 'subtle';
    }
  };

  if (loading) {
    return (
      <div className={classes.loadingContainer}>
        <Spinner size="large" label="加载中..." />
      </div>
    );
  }

  return (
    <div className={classes.dashboard}>
      {/* 统计卡片 */}
      <div className={classes.statsGrid}>
        <Card className={classes.statCard}>
          <div className={classes.statHeader}>
            <div className={`${classes.statIcon} ${classes.statIconPrimary}`}>
              <ContactCard20Regular />
            </div>
          </div>
          <div className={classes.statValue}>{stats.totalOpportunities}</div>
          <div className={classes.statLabel}>总商机数</div>
          <div className={`${classes.statChange} ${classes.changePositive}`}>
            <ArrowTrending20Regular />
            <span>较上月 +15%</span>
          </div>
        </Card>

        <Card className={classes.statCard}>
          <div className={classes.statHeader}>
            <div className={`${classes.statIcon} ${classes.statIconSuccess}`}>
              <DocumentBulletList20Regular />
            </div>
          </div>
          <div className={classes.statValue}>{stats.activeOpportunities}</div>
          <div className={classes.statLabel}>进行中商机</div>
          <div className={`${classes.statChange} ${classes.changePositive}`}>
            <ArrowTrending20Regular />
            <span>较上月 +8%</span>
          </div>
        </Card>

        <Card className={classes.statCard}>
          <div className={classes.statHeader}>
            <div className={`${classes.statIcon} ${classes.statIconWarning}`}>
              <Alert20Regular />
            </div>
          </div>
          <div className={classes.statValue}>{stats.weeklyNew}</div>
          <div className={classes.statLabel}>本周新增</div>
          <div className={`${classes.statChange} ${classes.changePositive}`}>
            <ArrowTrending20Regular />
            <span>较上周 +20%</span>
          </div>
        </Card>

        <Card className={classes.statCard}>
          <div className={classes.statHeader}>
            <div className={`${classes.statIcon} ${classes.statIconInfo}`}>
              <ContactCard20Regular />
            </div>
          </div>
          <div className={classes.statValue}>{formatNumber(stats.totalValue)}</div>
          <div className={classes.statLabel}>总价值 (万元)</div>
          <div className={`${classes.statChange} ${classes.changePositive}`}>
            <ArrowTrending20Regular />
            <span>较上月 +12%</span>
          </div>
        </Card>
      </div>

      {/* 主要内容区域 */}
      <div className={classes.mainContent}>
        {/* 左侧列 */}
        <div className={classes.leftColumn}>
          {/* 商机状态分布 */}
          <Card>
            <div className={classes.cardContent}>
              <div className={classes.cardHeader}>
                <div className={classes.cardTitle}>商机状态分布</div>
                <Button
                  appearance="subtle"
                  size="small"
                  icon={<Eye20Regular />}
                  onClick={() => navigate('/opportunities')}
                >
                  查看详情
                </Button>
              </div>
              <div className={classes.chartContainer}>
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={opportunityDistribution}
                      cx="50%"
                      cy="50%"
                      innerRadius={60}
                      outerRadius={120}
                      paddingAngle={5}
                      dataKey="value"
                    >
                      {opportunityDistribution.map((entry: any, index: number) => (
                        <Cell key={`cell-${index}`} fill={entry.color} />
                      ))}
                    </Pie>
                    <Tooltip />
                    <Legend />
                  </PieChart>
                </ResponsiveContainer>
              </div>
            </div>
          </Card>

          {/* 近期活动 */}
          <Card>
            <div className={classes.cardContent}>
              <div className={classes.cardHeader}>
                <div className={classes.cardTitle}>近期活动</div>
              </div>
              {activities.length === 0 ? (
                <div className={classes.emptyState}>暂无活动记录</div>
              ) : (
                activities.slice(0, 5).map((activity: any) => (
                  <div key={activity.id} className={classes.activityItem}>
                    <div 
                      className={classes.activityDot} 
                      style={{ backgroundColor: '#165DFF' }}
                    />
                    <div className={classes.activityContent}>
                      <div className={classes.activityTitle}>{activity.title}</div>
                      <div className={classes.activityTime}>
                        {new Date(activity.timestamp).toLocaleString('zh-CN')} - {activity.user}
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          </Card>
        </div>

        {/* 右侧列 */}
        <div className={classes.rightColumn}>
          {/* 待办事项 */}
          <Card>
            <div className={classes.cardContent}>
              <div className={classes.cardHeader}>
                <div className={classes.cardTitle}>待办事项</div>
                <Badge appearance="filled" color="danger">{todos.length}</Badge>
              </div>
              {todos.length === 0 ? (
                <div className={classes.emptyState}>暂无待办事项</div>
              ) : (
                todos.slice(0, 5).map((todo: any) => (
                  <div key={todo.id} className={classes.todoItem}>
                    <div className={classes.todoInfo}>
                      <div className={classes.todoTitle}>{todo.title}</div>
                      <div className={classes.todoMeta}>
                        截止: {new Date(todo.dueDate).toLocaleDateString('zh-CN')}
                        <Badge 
                          appearance="filled" 
                          color={getPriorityColor(todo.priority)}
                          className={classes.priorityBadge}
                          size="small"
                        >
                          {todo.priority === 'high' ? '高' : todo.priority === 'medium' ? '中' : '低'}
                        </Badge>
                      </div>
                    </div>
                    <Button
                      appearance="subtle"
                      size="small"
                      onClick={() => {
                        if (todo.opportunityId) {
                          navigate(`/opportunities/${todo.opportunityId}`);
                        }
                      }}
                    >
                      处理
                    </Button>
                  </div>
                ))
              )}
            </div>
          </Card>

          {/* 高价值商机提醒 */}
          <Card>
            <div className={classes.cardContent}>
              <div className={classes.cardHeader}>
                <div className={classes.cardTitle}>高价值商机</div>
                <Button
                  appearance="subtle"
                  size="small"
                  icon={<Eye20Regular />}
                  onClick={() => navigate('/opportunities')}
                >
                  查看全部
                </Button>
              </div>
              {highValueOpportunities.length === 0 ? (
                <div className={classes.emptyState}>暂无高价值商机</div>
              ) : (
                highValueOpportunities.map((opportunity: any) => (
                  <div key={opportunity.id} className={classes.highValueItem}>
                    <div className={classes.highValueInfo}>
                      <div className={classes.highValueName}>{opportunity.name}</div>
                      <div className={classes.highValueCustomer}>{opportunity.customer}</div>
                    </div>
                    <div className={classes.highValueMeta}>
                      <div className={classes.highValueAmount}>
                        {formatCurrency(opportunity.value)}
                      </div>
                      <Badge 
                        appearance="filled"
                        style={{ backgroundColor: getRiskColor(opportunity.risk), color: 'white' }}
                        size="small"
                      >
                        {opportunity.risk === 'high' ? '高风险' : 
                         opportunity.risk === 'medium' ? '中风险' : '低风险'}
                      </Badge>
                    </div>
                  </div>
                ))
              )}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
};

export default DashboardPage;
